from django.shortcuts import render

from rest_framework.response import Response
from rest_framework.views import  APIView
from .models import *
from utis.setu.stt import send_code
import  os,time,re,redis,json,random,string
from captcha.image import ImageCaptcha
from django.http import  HttpResponse
# Create your views here.

from  django.contrib.auth.hashers import make_password,check_password

#注册
class Ce(APIView):
    def post(self,request):
        mobile=request.data.get('mobile')
        password=request.data.get('password')
        if not all([password,mobile]):
            return Response({'code':206,'msg':'字段不完整'})
        if not re.findall('^1[3-9]\d{9}$',mobile):
            return Response({'code':207,'msg':'手机号不正确'})
        Usermodel.objects.create(
            mobile=mobile,
            password=make_password(password)
        )
        return Response({'code':200,'msg':'注册成功'})



#登录
class Deng(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        if not re.findall('^1[3-9]\d{9}$', mobile):
            return Response({'code': 207, 'msg':'手机号不正确'})
        return Response({'code':200,'msg':'登录成功'})



#图片验证码
class Tu(APIView):
    def get(self,request,uuid):
        set=''.join(random.sample(string.digits+string.ascii_letters,4))
        se=ImageCaptcha()
        img=se.generate(set)
        r=redis.Redis(host='localhost',port=6379,db=4)
        r.set(uuid,set,ex=120)
        r.save()
        return HttpResponse(img,content_type='image/png')


#短信验证码
class Duan(APIView):
    def get(self, request, mobile):
        if not re.findall("^1[3-9]\d{9}$", mobile):
            return Response({'code': 205, 'msg': '手机号不正确'})
        resp = send_code.delay(mobile)
        time.sleep(5)
        try:
            cls = redis.Redis(host='127.0.0.1', port=6379,db=6)
            key = 'celery-task-meta-' + resp.id
            redist = cls.get(key)
            if redist:
                dictr = json.loads(redist.decode())
                if dictr['status'] == 'SUCCESS':
                    dicte = json.loads(dictr['result'])
                    if dicte['statusCode'] == '112310' or dicte['statusCode'] == '000000':
                        return Response({'code': 200, 'msg': '验证码发送成功'})
                return Response({'code': 206, 'msg': '错误'})
            else:
                return Response({'code': 207, 'msg': '验证码发送失败'})
        except Exception as e:
            print('错误原因>>>>>>>', e)
            return Response({'code': 500, 'msg': '后端错误'})




#上传图片
from django.conf import settings
class Shang(APIView):
    def post(self, request):
        file = request.FILES.get('file')
        print('>>>>>>>>>>>>>', type(file), file)
        file_name = file.name
        print(">>>>>>>", file_name)
        # settings.STATICFILES_DIRS[0],'imgs/'
        file_dict = os.path.join(settings.STATICFILES_DIRS[0], 'imgs/')
        file_url = file_dict + file_name
        with open(file_url, 'wb') as f:
            f.write(file.file.read())
        return Response({'code': 200, 'msg': '上传成功', 'file_path': 'static/imgs/', 'file_name': file_name})


#分类
class Lei(APIView):
    def get(self,request,):
       set=BookCateModel.objects.all()
       list=[]
       for  i in set:
           list.append({
               'id':i.id,
               'name':i.name,
           })
       return Response({'code':200,'msg':'ok','list':list})


#类型
class Xing(APIView):
    def get(self,request):
        set=request.query_params.get('id')
        se=BookModel.objects.filter(tt=set)
        list=[]
        for i in se:
            list.append({
                'id':i.id,
                'name':i.name,
                'zhu':i.zhu,
                'img':i.img,
                'shou':i.shou,
                'tt':i.tt_id,
            })
        return Response(list)



#展示用户信息
class Zhan(APIView):
    def get(self,reequest):
        set=Usermodel.objects.all()
        list=[]
        for i in set:
            list.append({
                'id':i.id,
                'name':i.name,
                'di':i.di,
                'wo':i.wo,
                'xin':i.xin,
                'shen':i.shen,
                'xuan':i.xuan,
            })
        return Response(list)



#头像
class To(APIView):
    def get(self, request):
        set = Collection.objects.all()
        list = []
        for i in set:
            list.append({
                'id': i.id,
                'img': i.img,
            })
        return Response(list)



#修改头像
class Xiang(APIView):
    def get(self,request,id):
        set=Collection.objects.get(id=id)
        list = {
                'id': set.id,
                'img': set.img,

            }
        return Response({'code': 200, 'msg': 'OK', 'data': list})


    def put(self,request,id):
       img=request.data.get('img')
       Collection.objects.filter(id=id).update(img=img)
       return Response({'code': 200, 'msg': "修改成功"})


#修改
class Gai(APIView):
    def put(self,request,id):
        try:
            c1=BookModel.objects.get(id=id, shou=0)
            c1.shou=1
            c1.save()
            return Response({'code': 200, 'msg': '收藏成功'})
        except Exception as e:
            print(e)
            user = BookModel.objects.get(id=id)
            return Response({'code': 400, 'msg': "已收藏了"})



#展示收藏
class Cang(APIView):
    def get(self,request):
        se=BookModel.objects.filter(shou=1)
        list=[]
        for i in se:
            list.append({
                'id':i.id,
                'name':i.name,
                'zhu':i.zhu,
                'img':i.img,
                'shou':i.shou,
            })
        return Response(list)


#修改收藏
class Ga(APIView):
    def put(self,request,id):
        try:
            c1 = BookModel.objects.get(id=id, shou=1)
            c1.shou = 0
            c1.save()
            return Response({'code': 200, 'msg': '取消收藏'})
        except Exception as e:
            print(e)
            user = BookModel.objects.get(id=id)
            return Response({'code': 400, 'msg': "已取消"})